<template>
  <el-form :model="ruleForm" :rules="rules" ref="validateForm" class="login-ruleForm">
    <el-form-item prop="username">
      <el-input v-model="ruleForm.username" id="user" placeholder="账号">
        <template #prefix>
          <icon-user theme="outline" size="16" fill="#999" />
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="ruleForm.password"
        @keyup.enter="handleLogin"
        placeholder="密码"
        type="password"
        id="password"
        show-password
      >
        <template #prefix>
          <icon-lock theme="outline" size="16" fill="#999" />
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <div class="login-check">
        <el-checkbox v-model="checkedPwd">记住我</el-checkbox>
      </div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" :loading="loading" class="login-btn" round @click="handleLogin">
        登录</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script>
import { reactive, toRefs, ref, unref, watch, onMounted } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { localGet, localSet, localRemove } from "@/utils/auth";
export default {
  setup() {
    const store = useStore();
    const router = useRouter();
    const validateForm = ref(null);
    const state = reactive({
      ruleForm: {
        username: "",
        password: "",
      },
      loading: false,
      checkedPwd: false,
      redirect: undefined,
      rules: {
        username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    });

    watch(
      () => router.currentRoute,
      ({ _value }) => {
        const route = _value;
        state.redirect = (route.query && route.query.redirect) || "/";
      },
      {
        immediate: true,
      }
    );
    // 根据是否"记住我"，动态设置本地缓存rememberMe字段
    watch(
      () => state.checkedPwd,
      (nv) => {
        localSet("rememberMe", nv);
        if (!nv) {
          localRemove("username");
          localRemove("password");
        }
      }
    );
    const setLocalUser = () => {
      localSet("username", state.ruleForm.username);
      localSet("password", state.ruleForm.password);
    };

    const handleLogin = async () => {
      if (state.checkedPwd) {
        setLocalUser();
      }
      const form = unref(validateForm);
      if (!form) return;
      await form.validate((valid) => {
        if (valid) {
          state.valid = true;
          state.loading = true;
          store
            .dispatch("user/login", {
              userName: state.ruleForm.username,
              passWord: state.ruleForm.password,
            })
            .then(() => {
              const routerPath =
                state.redirect === "/404" || state.redirect === "/401" ? "/" : state.redirect;
              router.push(routerPath).catch(() => {});
              state.loading = false;
            })
            .catch(() => {
              state.loading = false;
            });
        }
      });
    };
    onMounted(() => {
      // 初始化获取本地是否"记住我"
      state.checkedPwd = !!localGet("rememberMe");
      // 记住账号则设置账号密码
      if (state.checkedPwd) {
        state.ruleForm.username = localGet("username");
        state.ruleForm.password = localGet("password");
      }
    });
    return {
      ...toRefs(state),
      validateForm,
      handleLogin,
    };
  },
};
</script>
<style lang="scss" scoped>
.login-ruleForm {
  margin-top: 1rem;
  :deep(.el-input__prefix) {
    top: 2px;
    padding: 0 4px;
  }
  .login-methods {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-around;
  }
  .login-btn {
    width: 100%;
  }
  .login-check {
    width: 100%;
    display: flex;
    align-content: center;
    justify-content: space-between;
  }
}
</style>
